package com.ydl.iec.iec104.server.handler;

import com.ydl.iec.iec104.common.CommonUtils;
import com.ydl.iec.iec104.common.Iec104Constant;
import com.ydl.iec.iec104.common.TelemeteringData;
import com.ydl.iec.iec104.message.Analysis;
import com.ydl.iec.iec104.util.ByteUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 *
* @ClassName: Check104Handler
* @Description: 检查104报文
* @author YDL
* @date 2020年5月13日
 */
public class Check104Handler extends ChannelInboundHandlerAdapter {
	/**存储缓存数据**/
	public static List<TelemeteringData> resultList;
	public static ArrayList<Object> list;
	private static final Logger LOGGER = LoggerFactory.getLogger(ChannelInboundHandlerAdapter.class);

	/**
	 * 拦截系统消息
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		LOGGER.info ("拦截的ChannelHandlerContext为："+ctx.channel ().toString ());
		ByteBuf result = (ByteBuf) msg;
		byte[] bytes = new byte[result.readableBytes()];
		result.readBytes(bytes);
		LOGGER.info("接收到的报文: " + ByteUtil.byteArrayToHexString(bytes));
		String analysis = Analysis.analysis(ByteUtil.byteArrayToHexString(bytes).replaceAll(" ", ""));
//		LOGGER.info("转换为数据: " + analysis);
		ArrayList<Object> list = new ArrayList<>();

		if (analysis.contains("遥测")) {
			String data = analysis.split("遥测1IEEE STD745短浮点数:")[1];
			String[] split = data.split("短浮点数:");
			for (String s : split) {
				String s1 = s.split("\n遥测")[0];
				if (s1.contains("\n")) {
					list.add(s1.split("\n")[0]);
				} else {
					list.add(s1);
				}
			}
			List<TelemeteringData> resultList = new ArrayList<>();
			LOGGER.info("listSize: " + list.size());
			if (list.size() == 39) {
				for (int i = 1; i < list.size()+1; i++) {
					resultList.add(new TelemeteringData(CommonUtils.getSbms(i), CommonUtils.getdms(i), i, CommonUtils.getdh(i), list.get(i - 1).toString(), i < 10 ? "100002400" + i : "10000240" + i));
				}
			}
			if (resultList.size()>0){
				insertCache(resultList,list);
			}
		}


		if (bytes.length < Iec104Constant.APCI_LENGTH || bytes[0] != Iec104Constant.HEAD_DATA) {
			LOGGER.error("报文无效");
			ReferenceCountUtil.release(result);
		} else {
			result.writeBytes(bytes);
			ctx.fireChannelRead(msg);
		}


	}
	/**
	 * 更新缓存数据
	 */
	public static void insertCache(List<TelemeteringData> resultList1,ArrayList<Object> list1){
		resultList = resultList1;
		list = list1;
		LOGGER.info(resultList.size()+"条数据已加载到缓存!");
	}
	/**
	 * 清理缓存数据
	 */
	public static void clearCache(){
		resultList.clear();
	}
}
